from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
import redis
import random
import hashlib
import time

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
redis_client = redis.Redis(host='localhost', port=6379, db=0)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password_hash = db.Column(db.String(120), nullable=False)
    created_at = db.Column(db.DateTime, default=db.func.now())

def generate_code():
    return ''.join(random.choices('0123456789', k=6))

with app.app_context():
    db.create_all()

@app.route('/send_verification_code', methods=['POST'])
def send_verification_code():
    email = request.json.get('email')
    if not email:
        return jsonify({'success': False, 'message': '请提供邮箱'}), 400
    code = generate_code()
    redis_client.setex(f"verification:{email}", 300, code)
    print(f"已生成验证码 {code} 并存储，需手动发送至 {email}")
    return jsonify({'success': True, 'message': '验证码已生成'})

@app.route('/register', methods=['POST'])
def register():
    email = request.json.get('email')
    password = request.json.get('password')
    code = request.json.get('verification_code')
    if not all([email, password, code]):
        return jsonify({'success': False, 'message': '参数不全'}), 400
    
    stored_code = redis_client.get(f"verification:{email}")
    if not stored_code or stored_code.decode() != code:
        return jsonify({'success': False, 'message': '验证码无效或已过期'}), 400
    
    if User.query.filter_by(email=email).first():
        return jsonify({'success': False, 'message': '邮箱已注册'}), 400
    
    password_hash = hashlib.sha256(password.encode()).hexdigest()
    new_user = User(email=email, password_hash=password_hash)
    db.session.add(new_user)
    db.session.commit()
    redis_client.delete(f"verification:{email}")
    return jsonify({'success': True, 'message': '注册成功'})

@app.route('/login', methods=['POST'])
def login():
    email = request.json.get('email')
    password = request.json.get('password')
    if not all([email, password]):
        return jsonify({'success': False, 'message': '参数不全'}), 400
    
    user = User.query.filter_by(email=email).first()
    if not user:
        return jsonify({'success': False, 'message': '用户不存在'}), 400
    
    password_hash = hashlib.sha256(password.encode()).hexdigest()
    if user.password_hash != password_hash:
        return jsonify({'success': False, 'message': '密码错误'}), 400
    
    return jsonify({'success': True, 'message': '登录成功'})

if __name__ == '__main__':
    app.run(debug=True)